//
//  MarketPullView.m
//  cityCar
//
//  Created by 常宽 on 14/11/5.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//
#import "MarketPullView.h"
#import "Connection.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "CKMarket.h"
@implementation MarketPullView

- (void)dealloc
{
    [_city release];
    [_province release];
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.bigArray = [NSMutableArray array];
        self.city = [NSString string];
        self.province = [NSString string];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self setupRefresh];
}
- (void)netWrok
{
    NSString *str = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v2/cms/channels/55555?pageNo=%d&pageSize=20&pro=%@&city=%@&v=4.0.0", self.countx, self.province, self.city];
    NSLog(@"网址:str %@", str);
    [Connection networkHandlerWith:str block:^(id result) {
        
        NSMutableArray *array = [result objectForKey:@"data"];
        
        for (NSDictionary *dic in array) {
            
            CKMarket *market = [[CKMarket alloc]init];
            [market setValuesForKeysWithDictionary:dic];
            [self.bigArray addObject:market];
            [market release];
        }
        
//        [self.collectionView reloadData];
        
    }];
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.collectionView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.collectionView footerEndRefreshing];
        self.countx += 1;
        NSLog(@"self.countx %d", self.countx);
    });
    
    
    
}
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.collectionView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.collectionView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.collectionView addFooterWithTarget:self action:@selector(netWrok)];
    [self.collectionView footerEndRefreshing];
    
//    self.countx = 2;
//    NSLog(@"se.countx %d", self.countx);
}
#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 刷新表格
        [self.collectionView reloadData];
        //        [_tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.collectionView  headerEndRefreshing];
    });
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //    NSLog(@"selected:%ld",indexPath.item);
    // 获得ID
    CKMarket *car = [self.bigArray objectAtIndex:indexPath.item];

    self.block(car);
    
}

@end
